package pl.jad.database.table.row;

import java.lang.reflect.Array;

import pl.jad.database.table.Table;
import pl.jad.database.table.column.ArrayIndexTableColumn;
import pl.jad.database.table.column.IndexTableColumn;
import pl.jad.database.table.column.TableColumn;

public class TableRows extends TableRow {

	public TableRows(Table table, Object object) {
		super(table, object);
		
		if (!object.getClass().isArray()) {
			throw new IllegalArgumentException("Object must be Array type");
		}
	}

	public String getInsertSql() throws Exception {
		int length = Array.getLength(this._object);
		
		StringBuilder sb = new StringBuilder();
		
		sb.append("INSERT INTO `" + this._table.getName() +"`(");
		for (TableColumn column : this._table.getColumns()) {
			sb.append("`" + column.getName() + "`, ");
		}
		sb.delete(sb.length() - 2, sb.length());
		
		sb.append(") VALUES ");
		for (int i = 0; i < length; i++) {
			sb.append("(");
			
			for (TableColumn column : this._table.getColumns()) {
				//System.out.println(sb.toString());
				if (column.getClass() == ArrayIndexTableColumn.class) {
					// indeks w tablicy
					sb.append(i);
				} else if (column.getClass() == IndexTableColumn.class){
					// unikalne id tabeli
					sb.append(column.getSqlFieldValue(this._object));
				} else {
					/*Object obj = Array.get(this._object, i);
					Class<?> c = obj.getClass();*/
					
					//System.out.println("rows: " + c.getName());
					sb.append(column.getSqlFieldValue(Array.get(this._object, i)));
					
					/*if (c == Boolean.class || c == boolean.class) {
						sb.append(obj.toString());
					} else {
						sb.append("'" + Array.get(this._object, i).toString() + "'");
					}*/
				}
				sb.append(", ");
			}
			sb.delete(sb.length() - 2, sb.length());
			
			sb.append("), ");
		}
		// delete ", "
		sb.delete(sb.length() - 2, sb.length());
		sb.append(";");
		
		return sb.toString();
	}
}
